<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>权限列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="rolesList" border stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['vcenter', 'bdbottom', i === 0 ? 'bdtop' : '']"
                            v-for="(item1, i) in scope.row.children" :key="item1.id">
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                                    {{ item1.authName }}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="19">
                                <el-row :class="[i1 === 0 ? '' : 'bdtop', 'vcenter',]"
                                    v-for="(item2, i1) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">
                                            {{ item2.authName }}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id"
                                            closable @close="removeRightById(scope.row, item3.id)">
                                            {{ item3.authName }}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditRoles(scope.row.id)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete"
                            @click="removeRolesById(scope.row.id)">删除
                        </el-button>
                        <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightDialogVisible(scope.row)">
                            分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-dialog title="添加角色" :visible.sync="addRolesDialogVisible" width="30%" @close="addRolesDialogClosed">
            <el-form :model="rolesForm" :rules="rolesFormRules" ref="rolesFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="rolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="rolesForm.roleDesc"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRolesDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="修改角色" :visible.sync="editRolesDialogVisible" width="30%" @close="editRolesDialogClosed">
            <el-form :model="editRolesForm" :rules="editRolesFormRules" ref="editRolesFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRolesForm.roleDesc"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRolesDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRolesInfo">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="30%" @close="setRightDialogClosed">
            <el-tree :data="setRightList" :props="treeProps" show-checkbox node-key="id" default-expand-all  
            :default-checked-keys='defKeys'
            ref="treeRef"
            ></el-tree>

            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRight">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    name: 'Roles',
    data() {
        return {
            rolesList: [],
            addRolesDialogVisible: false,
            rolesForm: {
                roleName: '',
                roleDesc: ''
            },
            rolesFormRules: {
                roleName: [
                    { required: true, message: '请输入角色名', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 3 到 6 个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入描述', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ]
            },
            editRolesDialogVisible: false,
            editRolesForm: {},
            editRolesFormRules: {
                roleName: [
                    { required: true, message: '请输入角色名', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 3 到 6 个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入描述', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ]
            },
            setRightDialogVisible: false,
            setRightList: [],
            treeProps: {
                children: 'children',
                label: 'authName'
            },
            defKeys:[],
            roleId:[]
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        async getRolesList() {
            const { data: res } = await axios.get('roles')
            if (res.meta.status !== 200) {
                return this.$message.error('获取角色列表失败')
            }
            this.rolesList = res.data

        },
        async removeRightById(role, rightId) {
            const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)

            if (result !== 'confirm') {
                return this.$message.info('取消了删除')
            }
            const { data: res } = await axios.delete(`roles/${role.id}/rights/${rightId}`)
            if (res.meta.status !== 200) {
                return this.$message.error('删除权限失败')
            }
            role.children = res.data

        },
        addRolesDialogClosed() {
            this.$refs.rolesFormRef.resetFields()

        },
        addRoles() {
            this.$refs.rolesFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await axios.post('roles', { roleName: this.rolesForm.roleName, roleDesc: this.rolesForm.roleDesc })
                if (res.meta.status !== 201) {
                    return this.$message.error('添加角色失败')
                }

                this.$message.success('添加角色成功')
                this.addRolesDialogVisible = false
                this.getRolesList()
            })

        },
        async showEditRoles(id) {
            const { data: res } = await axios.get('roles/' + id)
            if (res.meta.status !== 200) {
                return this.$message.error('查询角色失败')
            }

            this.editRolesForm = res.data
            this.editRolesDialogVisible = true
        },
        editRolesDialogClosed() {
            this.$refs.editRolesFormRef.resetFields()
        },
        editRolesInfo() {
            this.$refs.editRolesFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await axios.put('roles/' + this.editRolesForm.roleId, { roleName: this.editRolesForm.roleName, roleDesc: this.editRolesForm.roleDesc })
                

                if (res.meta.status != 200) {
                    this.$message.error('更新角色信息失败')
                }
                this.$message.success('更新角色信息成功')
                this.editRolesDialogVisible = false
                this.getRolesList()
            })
        },
        async removeRolesById(id) {
            const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            console.log(result);
            if (result !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res } = await axios.delete('roles/ ' + id)
            if (res.meta.status !== 200) {
                return this.message.error('删除角色失败')
            }
            this.$message.success('删除角色成功')

            this.getRolesList()
        },
        async showSetRightDialogVisible(role) {
            this.roleId = role.id
            const { data: res } = await axios.get('rights/tree')
            if (res.meta.status !== 200) {
                return this.$message.error('获取权限数据失败')
            }
            this.setRightList = res.data
            console.log(this.setRightList);
            this.getLeafKeys(role,this.defKeys)
            this.setRightDialogVisible = true
        },
        getLeafKeys(node,arr){
            if(!node.children){
                return arr.push(node.id)
            }
            node.children.forEach(element => {
                this.getLeafKeys(element,arr)
            });
        },
        setRightDialogClosed() {
            this.defKeys = []
        },
        async allotRight(){
            const keys = [
                ...this.$refs.treeRef.getCheckedNodes(),
                ...this.$refs.treeRef.getCheckedKeys()
            ]
            const idStr = keys.join(',')
            const {data:res} = await axios.post(`roles/${this.roleId}/rights`,{rids:idStr})
            if(res.meta.status !== 200){
                return this.$message.error('分配权限失败')
            }
            this.$message.success('分配权限成功')
            this.getRolesList()
            this.setRightDialogVisible = false

        }

    },
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 7px;
}

.bdtop {
    border-top: 1px solid #eee;
}

.bdbottom {
    border-bottom: 1px solid #eee;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>